/*****IE下Map不支持的解决方案*****/
function Map() {
    this.elements = new Array();
    // 获取Map元素个数
    this.size = function () {
        return this.elements.length;
    };
    // 判断Map是否为空
    this.isEmpty = function () {
        return (this.elements.length < 1);
    };
    // 删除Map所有元素
    this.clear = function () {
        this.elements = new Array();
    };
    // 向Map中增加元素（key, value)
    this.put = function (_key, _value) {
        if (this.containsKey(_key) == true) {
            if (this.containsValue(_value)) {
                if (this.remove(_key) == true) {
                    this.elements.push({
                        key: _key,
                        value: _value
                    });
                }
            } else {
                this.elements.push({
                    key: _key,
                    value: _value
                });
            }
        } else {
            this.elements.push({
                key: _key,
                value: _value
            });
        }
    };
    // 向Map中增加元素（key, value)
    this.set = function (_key, _value) {
        if (this.containsKey(_key) == true) {
            if (this.containsValue(_value)) {
                if (this.remove(_key) == true) {
                    this.elements.push({
                        key: _key,
                        value: _value
                    });
                }
            } else {
                this.elements.push({
                    key: _key,
                    value: _value
                });
            }
        } else {
            this.elements.push({
                key: _key,
                value: _value
            });
        }
    };
    // 删除指定key的元素，成功返回true，失败返回false
    this.remove = function (_key) {
        var bln = false;
        try {
            for (var i = 0; i < this.elements.length; i++) {
                if (this.elements[i].key == _key) {
                    this.elements.splice(i, 1);
                    return true;
                }
            }
        } catch (e) {
            bln = false;
        }
        return bln;
    };
    // 删除指定key的元素，成功返回true，失败返回false
    this.del = function (_key) {
        var bln = false;
        try {
            for (var i = 0; i < this.elements.length; i++) {
                if (this.elements[i].key == _key) {
                    this.elements.splice(i, 1);
                    return true;
                }
            }
        } catch (e) {
            bln = false;
        }
        return bln;
    };
    // 获取指定key的元素值value，失败返回null
    this.get = function (_key) {
        try {
            for (var i = 0; i < this.elements.length; i++) {
                if (this.elements[i].key == _key) {
                    return this.elements[i].value;
                }
            }
        } catch (e) {
            return null;
        }
    };
    // set指定key的元素值value
    this.setValue = function (_key, _value) {
        var bln = false;
        try {
            for (var i = 0; i < this.elements.length; i++) {
                if (this.elements[i].key == _key) {
                    this.elements[i].value = _value;
                    return true;
                }
            }
        } catch (e) {
            bln = false;
        }
        return bln;
    };
    // 获取指定索引的元素（使用element.key，element.value获取key和value），失败返回null
    this.element = function (_index) {
        if (_index < 0 || _index >= this.elements.length) {
            return null;
        }
        return this.elements[_index];
    };
    // 判断Map中是否含有指定key的元素
    this.containsKey = function (_key) {
        var bln = false;
        try {
            for (var i = 0; i < this.elements.length; i++) {
                if (this.elements[i].key == _key) {
                    bln = true;
                }
            }
        } catch (e) {
            bln = false;
        }
        return bln;
    };
    // 判断Map中是否含有指定key的元素
    this.has = function (_key) {
        var bln = false;
        try {
            for (var i = 0; i < this.elements.length; i++) {
                if (this.elements[i].key == _key) {
                    bln = true;
                }
            }
        } catch (e) {
            bln = false;
        }
        return bln;
    };
    // 判断Map中是否含有指定value的元素
    this.containsValue = function (_value) {
        var bln = false;
        try {
            for (var i = 0; i < this.elements.length; i++) {
                if (this.elements[i].value == _value) {
                    bln = true;
                }
            }
        } catch (e) {
            bln = false;
        }
        return bln;
    };
    // 获取Map中所有key的数组（array）
    this.keys = function () {
        var arr = new Array();
        for (var i = 0; i < this.elements.length; i++) {
            arr.push(this.elements[i].key);
        }
        return arr;
    };
    // 获取Map中所有value的数组（array）
    this.values = function () {
        var arr = new Array();
        for (var i = 0; i < this.elements.length; i++) {
            arr.push(this.elements[i].value);
        }
        return arr;
    };
    /**
     * map遍历数组
     * @param callback [function] 回调函数；
     * @param context [object] 上下文；
     */
    this.forEach = function forEach(callback, context) {
        context = context || window;
        //IE6-8下自己编写回调函数执行的逻辑
        var newAry = new Array();
        for (var i = 0; i < this.elements.length; i++) {
            if (typeof callback === 'function') {
                var val = callback.call(context, this.elements[i].value, this.elements[i].key, this.elements);
                newAry.push(this.elements[i].value);
            }
        }
        return newAry;
    }
}

/*****End*****/
//页面渲染Gui
var objScreen = {
    mrListId: $("#mrListId").val(),
    entityId: $("#entityId").val(),
    formCheckType: $("#formCheckType").val(),
    reUploadFlag: $("#reUploadFlag").val(),
    isShowSourceData: $("#isShowSourceData").val(),
    isMergeReport: $("#isMergeReport").val(),
    mrType: $("#mrType").val(),
    EMRPagePath: $('#EMRPagePath').val().replace(/dhcc-/g, "\'"),
    layerIndex: -1,
    formData: {},  //表单项目数据
    // EditVal: new Array(),
    // EditItem: new Array(),
    EditItemVal: new Map,   //全局变量 编辑值
    addListener: 0,
    initFlg: 0,   //全表单校验标识
    validCat: new Array(),    //记录表单涉及的分类
    operStartTime: 0
};

/**
 * 函数防抖动封装。
 * 用于限制函数调用的频率，当调用过快时，只有最后一次调用会被执行。
 *
 * @param {Function} func 要被防抖的函数。
 * @param {number} wait 等待时间，单位为毫秒。
 * @param {boolean} immediate 是否立即执行，如果为true，则在第一次调用时立即执行，之后的调用在等待期内不会执行。
 * @returns {Function} 返回一个防抖后的函数。
 */
function debounce(func, wait, immediate) {
    var timeoutId, result;

    /**
     * 防抖动函数。
     * 通过取消重置的定时器来实现函数调用的限制。
     */
    var debouncedFunction = function() {
        var context = this,
            args = arguments;
        clearTimeout(timeoutId); // 取消当前的定时器，以防止不必要的函数执行。

        // 如果是立即执行模式，并且没有设定过定时器，则立即执行函数。
        if (immediate && !timeoutId) {
            result = func.apply(context, args);
        }

        // 设定一个新的定时器，如果定时器过期后没有被取消，则执行原始函数。
        timeoutId = setTimeout(function() {
            timeoutId = null; // 重置定时器标识，以便它可以被再次设置。
            if (!immediate) {
                result = func.apply(context, args);
            }
        }, wait);

        // 返回可能已经执行的结果，这在立即执行模式下特别有用。
        return result;
    };

    // 添加一个取消方法，用于在需要时直接取消防抖函数的执行。
    debouncedFunction.cancel = function() {
        clearTimeout(timeoutId);
        timeoutId = null;
    };

    // 返回封装后的防抖函数。
    return debouncedFunction;
}


function decodeUnicode(str) {
    str = str.replace(/\\/g, "%");
    // 转换中文
    str = unescape(str);
    // 将其他受影响的转换回原来
    str = str.replace(/%/g, "\\");
    // 对网址的链接进行处理
    str = str.replace(/\\/g, "");
    return str;
}

objScreen.InitViewScreen = function () {
    //提醒内容预留div
    $('#SDNotice').html('');
    layer.load();
    var url = '';
    if (objScreen.mrType == 1) {
        url = "/sdc/sdcqcformshow/getItemInfo/" + objScreen.mrListId
    } else {
        url = "/sds/sdsqcformshow/getItemInfo/" + objScreen.mrListId
    }
    // 获取表单项目信息
    var ajax = new $ax(url, function (data) {
        objScreen.formdata = data;
        var isShowDataTrace = objScreen.formdata[0].isShowDataTrace;
        for (var i = objScreen.formdata.length - 1; i >= 0; i--) {
            var item = objScreen.formdata[i];
            var itemId = item.id;
            var itemCode = item.btCode;
            var Value = item.execResult;
            var text = item.execResultText;
            var EditPower = item.editPower;
            var ItemCat = item.btItemCat;
            var ItemSubCat = item.btItemSubCat;
            // var ItemSourceData = item.itemSourceData;
            if ($('#' + itemId).length == 0) {
                layer.closeAll('loading');
                $.messager.alert("错误提示", "表单模板错误，请联系支持人员更新模板！", 'error');
                return;
            }
            // 项目源数据title
            /* if (ItemSourceData != "") {
                 $('#' + itemId).attr("popContent", ItemSourceData);
                 $('#' + itemId).popover({content: ItemSourceData, trigger:'hover', width:'500px', placement:'auto-right'});
             }*/
            // 如果有配置启用显示数据源的功能，则增加hover显示
            if (objScreen.isShowSourceData == 'Y') {
                $('#' + itemId).popover({
                    type: 'async',
                    url: '/sds/sdsqcformshow/getItemSourceDetail?mrListId=' + objScreen.mrListId + "&formItemId=" + itemId,
                    content: function (data) {
                        return data.message;
                    },
                    trigger: 'hover',
                    width: '500px',
                    placement: 'auto-right'
                });
            }

            //记录表单大类信息
            // if (objScreen.validCat.indexOf(ItemCat) < 0) objScreen.validCat.push(ItemCat); // IE8及以下不支持对象的indexOf
            if ($.inArray(ItemCat, objScreen.validCat) == -1) objScreen.validCat.push(ItemCat);
            if (EditPower == '0') {
                $('#' + itemId + "_Row").css({'display': 'none'});
                //判断子标题是否需要收起来
                if ($('#' + itemId + "_Row").prev()[0].className == 'itemsubCat') {
                    $('#' + itemId + "_Row").prev().css({'display': 'none'});
                }
                // 记录该项目初始值
                $('#' + itemId).attr("InitVal", Value);
                $('#' + itemId).attr("InitText", text);
            } else {
                var itemclass = $('#' + itemId)[0].className
                if (itemclass.indexOf('Combo') > -1) {
                    var multi = false;
                    if (itemclass.indexOf('mul') > -1) multi = true;
                    objScreen.CreatCombo(itemId, multi);
                    $('#' + itemId).combobox('setValue', Value, text);
                } else if (itemclass == 'RadioGroup') {
                    Common_RadioToSDDic(itemId, itemId);
                    //给单选列表赋值
                    $('[name="' + itemId + '"][value="' + Value + '"]').radio('setValue', true);
                } else if (itemclass == 'CheckGroup') {
                    Common_CheckboxToSDDic(itemId, itemId, 1);
                    var valArr = Value.split(',');
                    //循环给多选列表赋值
                    for (var j = 0; j < valArr.length; j++) {
                        if (valArr[j] == "") continue;
                        $('[name=' + itemId + '][value=' + valArr[j] + ']').radio('setValue', true);
                    }
                } else {
                    $('#' + itemId).val(Value);
                }
                if (Value == "") {
                    //$('#' + itemId + '_Source').addClass("icon icon-search")
                    //$('#' + itemId + '_Source').attr("title","参考数据源")
                } else {
                    if ("Y" == isShowDataTrace) {
                        $('#' + itemId + '_Source').addClass("icon-target-arrow");
                        $('#' + itemId + '_Source').attr("title", "数据源已匹配");
                    }
                }
                // 记录该项目是否被渲染过
                $('#' + itemId).attr("InitFlg", 1);
            }
        }
        objScreen.addListener = 1;
        layer.closeAll('loading');

        objScreen.operStartTime = getNowFormatDate();

        // 计算各章节必填项目数和已完成数
        objScreen.CalculateChapter();
    }, function () {
        layer.closeAll('loading');
    });
    ajax.setAsync();
    ajax.start();

    //生成字典列表
    // $(".CheckGroup").each(function (i, v) {
    //     Common_CheckboxToSDDic(v.id, v.id, 1);
    // });
    // $(".RadioGroup").each(function (i, v) {
    //     Common_RadioToSDDic(v.id, v.id);
    // });
}

objScreen.LoadEvent = function () {
    // 监听表单区域滚动条，改变锚点样式
    $("#FormContent").scroll(function(){
        // 获取最上方的元素
        var topElement;
        var minDistance = Infinity;

        $('.itemCat').each(function() {
            var distance = Math.abs($(this).offset().top - $("#FormContent").offset().top);
            if (distance < minDistance) {
                minDistance = distance;
                topElement = $(this);
            }
        });

        // 在滚动时更新锚点的样式
        $("#anchor li a").removeClass("anchor-current");
        $("#anchor li a[href='#" + topElement.attr('id') + "']").addClass("anchor-current");
    });


    $('input').click(function () {
        var itemId = $(this)[0].id;
        var itemclass = $(this)[0].className;
        if (itemclass.indexOf('Combo') > -1) {
            var multi = false;
            if (itemclass.indexOf('mul') > -1) multi = true;
            objScreen.CreatCombo(itemId, multi);
            $('#' + itemId).combobox('showPanel');
        } else if (itemclass.indexOf('Date') == 0) {
            if (itemclass.indexOf('T') > -1) {
                $('#' + itemId).datetimebox({
                    width: $(".itemCat").outerWidth() * 0.35, //$(".itemTR div").outerWidth(),
                    editable: false,
                    onChange: function (v) {
                        objScreen.fireEvent($(this)[0].id, v);
                    },
                    onShowPanel: function (v) {
                        $('#' + itemId + '_T').remove();
                    },
                    onHidePanel: function (v) {
                        $('#' + itemId + '_Note').after('<span class="clearDate" id=' + itemId + '_T style="color:blue;margin-left:10px;cursor:pointer;">清空日期时间</span>');
                    }
                });
                $('#' + itemId).datetimebox('showPanel');
            } else {
                $('#' + itemId).datebox({
                    width: $(".itemCat").outerWidth() * 0.35, //$(".itemTR div").outerWidth(),
                    editable: false,
                    onChange: function (v) {
                        objScreen.fireEvent($(this)[0].id, v);
                    },
                    onShowPanel: function (v) {
                        $('#' + itemId + '_D').remove();
                    },
                    onHidePanel: function (v) {
                        $('#' + itemId + '_Note').after('<span class="clearDate" id=' + itemId + '_D style="color:blue;margin-left:10px;cursor:pointer;">清空日期</span>');
                    }
                });
                $('#' + itemId).datebox('showPanel');
            }
        } else if (itemclass == 'Num') {
            $('#' + itemId).numberbox({
                precision: 2,
                parser: function (num) {
                    //未输入不做转换
                    if (num == "") {
                        return num;
                    }
                    var num = parseFloat(num)
                    if (isNaN(num)) {
                        return '';
                    } else {
                        return parseFloat(num);
                    }
                },
                width: $(".itemCat").outerWidth() * 0.35 //$(".itemTR div").outerWidth()
            });
            $(this).focus();
        } else if (itemclass == 'Integer') {
            $('#' + itemId).numberbox({
                isKeyupChange: true,
                onChange: function (v) {
                    objScreen.fireEvent($(this)[0].id, v);
                },
                width: $(".itemCat").outerWidth() * 0.35 //$(".itemTR div").outerWidth()
            });
            $(this).focus();
        }
    })
    $('.Text,.Integer,.Num').on('input', function () {
        objScreen.fireEvent($(this)[0].id, $(this).val());
    })
    // 日期框、数值框粘贴事件，自动触发click事件，解决粘贴内容有非法字符绕过数据校验的问题
    $('.Date,.DateT,.Integer,.Num').on('paste', function () {
        $(this).click();
    })
    $('.Text').on('change', function () {
        objScreen.fireEvent($(this)[0].id, $(this).val());
    })
    $('.Num').on('change', function () {
        Value = $(this).val().replace(/[^\d.-]/g, "");
        $(this).val(Value);
        objScreen.fireEvent($(this)[0].id, $(this).val());
    })
    $('.itemTR').on('click', '.clearDate', function () {
        var nodeID = $(this)[0].id;
        var dateID = nodeID.split('_')[0];
        var type = nodeID.split('_')[1];
        if (type == "T") {
            $('#' + dateID).datetimebox("setValue", "");
            $('#' + dateID).datetimebox("setText", "");
        } else {
            $('#' + dateID).datebox("setValue", "");
            $('#' + dateID).datebox("setText", "");
        }
        // objScreen.EditItemVal.del(dateID);
    })
    $('.item-source').on('click', function () {
        var itemId = $(this)[0].id;
        var title = $(this).attr('title');
        if (itemId != "") {
            var arr = itemId.split("_");
            if (title.indexOf("匹配") > -1) {
                var index = layer.open({
                    type: 2,
                    title: "病历溯源",
                    area: ['1200px', '650px'],
                    zIndex: 19911102,//这是个大坑！！！！ 默认是19891014 远远大于量表下拉框的zIndex 导致下拉框的数据看不到！！！
                    content: '/sds/sdsqcformshow/displaySumInfo?formItemId=' + arr[0] + "&entityId=" + objScreen.entityId + "&mrListId=" + objScreen.mrListId,
                    skin: 'layer-ext-hisui',
                    scrollbar: false//为了禁止父页面滚动条滚动
                });
                this.layerIndex = index;
            } else {
                var index = layer.open({
                    type: 2,
                    title: "表单项目表详情",
                    area: ['800px', '520px'],
                    zIndex: 19911102,//这是个大坑！！！！ 默认是19891014 远远大于量表下拉框的zIndex 导致下拉框的数据看不到！！！
                    content: '/sds/sdsqcformitem/to_update/' + arr[0],
                    skin: 'layer-ext-hisui',
                    scrollbar: false//为了禁止父页面滚动条滚动
                });
                this.layerIndex = index;
            }
        }

    })

    $('button').click(function () {
        var btcode = $(this)[0].id;
        switch (btcode) {
            case "Save":
            case "Submit":
                debounce(objScreen.saveReport(btcode),3000, true);
                break;
            case "Up":
                debounce(objScreen.upReport(btcode),3000, true);
                break;
            case "export":
                debounce(objScreen.ExportRep(),3000, true);
                break;
            case "Check":
                debounce(objScreen.checkReport(this),3000, true);
                break;
            default:
                debounce(objScreen.UpdateStatus(btcode),1000, true);
                break;
        }
    })
    $('#checkRep').on('click', debounce(function () {
        var ValiMsg = objScreen.valiForm('');
        if (ValiMsg) {
            $.messager.alert("错误提示", ValiMsg, 'error');
        } else {
            $.messager.alert('提示', '校验通过！', 'success');
        }
    },500,true))
    $('#expandRep').on('click', debounce(function () {
        for (var i = 0; i < objScreen.validCat.length; i++) {
            var xitemCat = objScreen.validCat[i];
            $('div[title="' + xitemCat + '"]').css({'display': 'block'});
            $('div[title="' + xitemCat + '"]').prev().removeClass('itemCat-fold');
        }
    },500,true))
    $('#collRep').on('click', debounce(function () {
        for (var i = 0; i < objScreen.validCat.length; i++) {
            var xitemCat = objScreen.validCat[i];
            $('div[title="' + xitemCat + '"]').css({'display': 'none'});
            $('div[title="' + xitemCat + '"]').prev().addClass('itemCat-fold');
        }
    },500,true))
    $('#toTopRep').on('click', debounce(function () {
        document.getElementById('SDNotice').scrollIntoView();
    },500,true))
    $('.score-table').on('click', debounce(function () {
        var scoreid = $(this).attr('id');
        var scoretitle = $(this).attr('title');
        var asmtId = scoreid.replace('_Score', '');
        //获取评分工具对应的项目
        var itemId = $(this).parent().attr('id').replace("_Row", "");
        objScreen.showEvalSheet(itemId, asmtId, scoretitle);
    },1000,true))
    $('#synFormData').on('click', debounce(function () {
        $.messager.progress({title: "提示", msg: '正在同步表单数据', text: '同步数据中....'});
        var ajax = new $ax("/sds/common/manualInitMrList", function (data) {
            $.messager.popover({msg: "表单数据同步成功！", type: 'success', timeout: 3000});
            $.messager.progress("close");
            $("#p1").panel('refresh');
        }, function (data) {
            $.messager.alert("表单数据同步错误!");
        });
        ajax.set({startDate: '', endDate: '', patientId: $("#episodeId").val(), deptId: '', entityId: $("#entityId").val()});
        ajax.setAsync(true);
        ajax.start();
    },5000,true))
    $('#showRule').on('click', debounce(function () {
        //打开 弹出框
        var index = layer.open({
            type: 2,
            title: '公告',
            area: ['50%', '80%'],
            zIndex: 19911102,//这是个大坑！！！！ 默认是19891014 远远大于量表下拉框的zIndex 导致下拉框的数据看不到！！！
            content: '/sds/sdsqcformshow/qcrule?entityId=' + objScreen.entityId,
            skin: 'layer-ext-hisui',
            scrollbar: false//为了禁止父页面滚动条滚动
        });
        this.layerIndex = index;
    },500,true))
    $('#showEmr').on(' click', debounce(function () {
        var PatientInfo = null;
        var ax = new $ax("/api/getadmxcode", function (data) {
            PatientInfo = data;
        });
        ax.set("mrListId", objScreen.mrListId);
        ax.start();
        var EpisodeID = PatientInfo.xcode;
        var PatientID = PatientInfo.patientCode;
        var postData = {};
        postData.EpisodeID = EpisodeID;
        postData.PatientID = PatientID;
        parent.postMessage(postData, "*");
        // parent.parent.window.showEmr(EpisodeID);
        //打开 弹出框
        // var index = layer.open({
        //     type: 2,
        //     title: '病历浏览',
        //     area: ['80%', '80%'],
        //     maxmin: true,
        //     zIndex: 19911102,//这是个大坑！！！！ 默认是19891014 远远大于量表下拉框的zIndex 导致下拉框的数据看不到！！！
        //     content: eval(objScreen.EMRPagePath),
        //     skin: 'layer-ext-hisui',
        //     shade: 0,
        //     scrollbar: false//为了禁止父页面滚动条滚动
        // });
        // this.layerIndex = index;
        var url = "https://10.10.107.4:1443/imedical/web/form.htm?TPSID=KPYSFXT&USERNAME=ys01&EpisodeID="+EpisodeID;
        window.open(url, 'new', 'location=no, toolbar=no');
    },500,true))
}
objScreen.InitMrButtons = function () {
    var url = '';
    if (objScreen.mrType == 1) {
        url = '/sdc/sdcqcformshow/mrState/' + objScreen.mrListId;
    } else {
        url = '/sds/sdsqcformshow/mrState/' + objScreen.mrListId;
    }
    var ajax = new $ax(url, function (StatCode) {
        if (StatCode == "") StatCode = "NotFilled";
        if (objScreen.reUploadFlag == "1") StatCode = "tUp";
        switch (StatCode) {
            case "I":
                $('#Save').show();
                $('#Submit').show();
                $('#O').show();
                $('#Check').hide();
                $('#Up').hide();
                $('#export').hide();
                $('#Back').hide();
                $('#FormStatus').text("已确认");
                break;
            case "Save":
                $('#Save').show();
                $('#Submit').show();
                $('#O').show();
                $('#Check').hide();
                $('#Up').hide();
                $('#export').hide();
                $('#Back').hide();
                $('#FormStatus').text("已保存");
                break;
            case "Submit":
                $('#Save').hide();
                $('#Submit').show();
                $('#O').show();
                $('#export').hide();
                var buttonText = '审核';
                if (objScreen.isMergeReport == "Y") {
                    buttonText = "审核+上报"
                }
                $('#Check').linkbutton({text: buttonText});
                // 如果医生直接上报，没有审核流程
                if (objScreen.formCheckType == "Y") {
                    $('#Check').hide();
                    if (objScreen.isMergeReport == "Y") {
                        $('#Up').hide();
                    } else {
                        $('#Up').show();
                    }
                    $('#Back').hide();
                } else {
                    $('#Check').show();
                    $('#Up').hide();
                    $('#Back').show();
                }
                $('#FormStatus').text("已提交");
                break;
            case "Back":
                $('#Save').show();
                $('#Submit').show();
                $('#Back').hide();
                $('#O').show();
                $('#Check').hide();
                $('#Up').hide();
                $('#export').hide();
                $('#FormStatus').text("已退回");
                break;
            case "O":
                $('#Save').hide();
                $('#Submit').hide();
                $('#Back').hide();
                $('#O').hide();
                $('#Check').hide();
                $('#Up').hide();
                $('#export').hide();
                $('#FormStatus').text("已排除");
                break;
            case "Check":
                $('#Save').hide();
                $('#Submit').hide();
                $('#export').hide();
                $('#Check').linkbutton({text: '取消审核'});
                // 如果医生直接上报，没有审核流程
                if (objScreen.formCheckType == "Y") {
                    $('#Check').hide();
                    $('#Up').show();
                    $('#Back').hide();
                    $('#O').show();
                } else {
                    $('#Check').show();
                    $('#Up').show();
                    $('#Back').show();
                    $('#O').hide();
                }
                $('#FormStatus').text("已审核");
                break;
            case "tUp":
                $('#Save').hide();
                $('#Submit').hide();
                $('#Back').hide();
                $('#O').hide();
                $('#Check').hide();
                $('#UnCheck').hide();
                $('#Up').show();
                $('#export').hide();
                $('#FormStatus').text(objScreen.reUploadFlag == "1"?"已上报":"测试上报");
                break;
            case "Up":
                $('#Save').hide();
                $('#Submit').hide();
                $('#Back').hide();
                $('#O').hide();
                $('#Check').hide();
                $('#Up').hide();
                $('#export').hide();
                $('#FormStatus').text("已上报");
                break;
            case "P":
                $('#Save').show();
                $('#Submit').hide();
                $('#Back').hide();
                $('#O').hide();
                $('#Check').hide();
                $('#Up').hide();
                $('#export').hide();
                $('#FormStatus').text("在院入组");
                break;
            default:
                $('#Save').hide();
                $('#Submit').hide();
                $('#Back').hide();
                $('#O').hide();
                $('#Check').hide();
                $('#Up').hide();
                $('#export').hide();
                $('#FormStatus').text("未知");
                break;
        }
    });
    ajax.setAsync();
    ajax.start();
}

objScreen.upReport = function (sCode) {
    // 如果是二次补报，则需要校验和保存数据
    if (objScreen.reUploadFlag == "1") {
        //填报值校验
        var valiMsg = "";
        var keyArr = objScreen.EditItemVal.keys();
        for (var i = 0, l = keyArr.length; i < l; i++) {
            var xcode = keyArr[i];
            var xNoteArr = xNote.split('<br>');
            for (var yind = 0; yind < xNoteArr.length; yind++) {
                var yNote = xNoteArr[yind];
                if (yNote.indexOf(':red') > -1) {
                    var einfo = $('#' + xcode + '_Row').children().first()[0].innerHTML + "-" + yNote;
                    valiMsg = valiMsg + einfo + "<br>";
                }
            }
        }
        if (valiMsg) {
            $.messager.alert("错误提示", valiMsg, 'error');
            return;
        }
        //数据保存
        var Err = "";
        var MrListID = $("#mrListId").val();
        var ExecUser = $("#execUser").val();

        for (var i = 0, l = keyArr.length; i < l; i++) {
            var itemId = keyArr[i];
            var itemVal = objScreen.EditItemVal.get(itemId);
            //提交信息
            var ajax = new $ax("/sds/sdsqcformshow/save", function (data) {
                if (data.code == 500) {
                    var itemDesc = $("#" + itemId).attr("title");
                    Err += itemDesc + ":" + itemVal + "<br>";
                }
            }, function (data) {
                var itemDesc = $("#" + itemId).attr("title");
                Err += itemDesc + ":" + itemVal + "<br>";
            });
            var params = {};
            params.mrListId = MrListID;
            params.execUser = ExecUser;
            params.itemId = itemId;
            params.itemVal = itemVal;
            ajax.setData(params);
            ajax.setAsync();
            ajax.start();
        }
        if (Err != "") {
            $.messager.progress("close");
            $.messager.alert("错误提示", "数据保存错误!键值明细:" + Err, 'info');
            return;
        }
    }
    $.messager.progress({
        title: "提示",
        msg: '正在上传数据',
        text: '上传中....'
    });
    var ajax = new $ax("/sds/sdsqcformshow/upload/" + objScreen.mrListId, function (UpRet) {
        $.messager.progress("close");
        if (UpRet.code == 1) {
            $.messager.popover({
                msg: '上传成功！',
                type: 'success',
                timeout: 1000,
                style: {
                    top: ($(window).height() - 50) / 2 + $(document).scrollTop(),
                    left: ($(window).width() - 140) / 2 + $(document).scrollLeft()
                }
            })
            //更新状态
            var ax = new $ax("/sds/sdsqcformshow/changeMrStatus", function (data) {
                $.messager.popover({
                    msg: '状态更新成功！',
                    type: 'success',
                    timeout: 1000,
                    style: {
                        top: ($(window).height() - 50) / 2 + $(document).scrollTop(),
                        left: ($(window).width() - 140) / 2 + $(document).scrollLeft()
                    }
                })
                objScreen.InitMrButtons();
            }, function (data) {
                $.messager.alert("错误提示", "状态更新错误!", 'info');
            });
            ax.set('mrListId', objScreen.mrListId);
            ax.set('status', sCode);
            ax.set('execUser', $("#execUser").val())
            ax.set('execUserId', $("#execUserId").val())
            ax.set('reason', '');
            ax.set('resume', UpRet.message);
            ax.set('operEndTime', getNowFormatDate());
            ax.setAsync(true);
            ax.start();
        } else if (UpRet.message.indexOf('重复') > -1) {
            //更新状态
            var ax = new $ax("/sds/sdsqcformshow/changeMrStatus", function (data) {
                $.messager.popover({
                    msg: '已存在上传记录，状态更新成功！',
                    type: 'success',
                    timeout: 1000,
                    style: {
                        top: ($(window).height() - 50) / 2 + $(document).scrollTop(),
                        left: ($(window).width() - 140) / 2 + $(document).scrollLeft()
                    }
                })
                objScreen.InitMrButtons();
            }, function (data) {
                $.messager.alert("错误提示", "已存在上传记录，状态更新错误!", 'info');
            });
            ax.set('mrListId', objScreen.mrListId);
            ax.set('status', sCode);
            ax.set('execUser', $("#execUser").val())
            ax.set('execUserId', $("#execUserId").val())
            ax.set('reason', '');
            ax.set('resume', UpRet.message);
            ax.set('operEndTime', getNowFormatDate());
            ax.setAsync(true);
            ax.start();
        } else {
            //追加日志
            var ax = new $ax("/sds/sdsqcincaseoperlog/add", function (data) {
            });
            ax.set('mrListId', objScreen.mrListId);
            ax.set('status', 'Up');
            ax.set('execUser', $("#execUser").val())
            ax.set('execUserId', $("#execUserId").val())
            ax.set('resume', UpRet.message);
            ax.set('operEndTime', getNowFormatDate());
            ax.setAsync(true);
            ax.start();
            $.messager.alert("错误提示", "表单上传失败!Error=" + UpRet.message, 'info');
        }
    }, function (data) {
        $.messager.alert("错误提示", "表单上传失败!", 'info');
    });
    ajax.setAsync();
    ajax.start();
}

objScreen.checkReport = function (that) {
    var CheckDesc = $(that).linkbutton("options").text;
    //根据按钮描述，采取审核/取消审核操作
    if (CheckDesc == "取消审核") {
        var CheckCode = "Submit";
    } else {
        var CheckCode = "Check";
        var valiMsg = objScreen.valiForm('');
        if (valiMsg) {
            $.messager.alert("错误提示", valiMsg, 'error');
            return;
        }
    }
    objScreen.UpdateStatus(CheckCode);
}

objScreen.saveReport = function (aCode) {
    if ((objScreen.EditItemVal.size == 0) && (aCode == 'Save')) {
        $.messager.alert("错误提示", "没有编辑过的项目需要保存", 'info');
        return;
    }
    //填报值校验
    var valiMsg = "";
    if (aCode == "Save") {
        var keyArr = objScreen.EditItemVal.keys();
        for (var i = 0, l = keyArr.length; i < l; i++) {
            var xcode = keyArr[i];
            var xNote = $('#' + xcode + '_Note').html();
            var xNoteArr = xNote.split('<br>');
            for (var yind = 0; yind < xNoteArr.length; yind++) {
                var yNote = xNoteArr[yind];
                if (yNote.indexOf(':red') > -1) {
                    var einfo = $('#' + xcode + '_Row').children().first()[0].innerHTML + "-" + yNote;
                    valiMsg = valiMsg + einfo + "<br>";
                }
            }
        }
        if (valiMsg) {
            $.messager.alert("错误提示", valiMsg, 'error');
            return;
        }
    } else {
        var valiMsg = objScreen.valiForm('');
        if (valiMsg) {
            $.messager.alert("错误提示", valiMsg, 'error');
            return;
        }
    }
    var SDesc = (aCode == "Save" ? "保存" : aCode == "Submit" ? "提交" : "");
    $.messager.confirm("提示", "是否" + SDesc + "这份病例?", function (r) {
        if (r) {
            $.messager.progress({
                title: "提示",
                msg: '正在' + SDesc + '数据',
                text: '上传中....'
            });
            var Err = "";
            var MrListID = $("#mrListId").val();
            var ExecUser = $("#execUser").val();

            var keyArr = objScreen.EditItemVal.keys();
            var url = '';
            if (objScreen.mrType == 1) {
                url = "/sdc/sdcqcformshow/save";
            } else {
                url = "/sds/sdsqcformshow/save";
            }
            for (var i = 0, l = keyArr.length; i < l; i++) {
                var itemId = keyArr[i];
                var itemVal = objScreen.EditItemVal.get(itemId);
                // }
                // for (var xind = 0; xind < objScreen.EditItem.length; xind++) {
                //     var itemId = objScreen.EditItem[xind];
                //     var itemVal = objScreen.EditVal[xind];
                //提交信息
                var ajax = new $ax(url, function (data) {
                    if (data.code == 500) {
                        var itemDesc = $("#" + itemId).attr("title");
                        Err += itemDesc + ":" + itemVal + "<br>";
                    }
                }, function (data) {
                    var itemDesc = $("#" + itemId).attr("title");
                    Err += itemDesc + ":" + itemVal + "<br>";
                });
                var params = {};
                params.mrListId = MrListID;
                params.execUser = ExecUser;
                params.itemId = itemId;
                params.itemVal = itemVal;
                ajax.setData(params);
                // ajax.setAsync();
                ajax.start();
            }
            if (Err != "") {
                $.messager.progress("close");
                $.messager.alert("错误提示", "数据保存错误!键值明细:" + Err, 'info');
            } else {
                $.messager.progress("close");
                $.messager.popover({
                    msg: '操作成功！',
                    type: 'success',
                    timeout: 1000,
                    style: {
                        top: ($(window).height() - 50) / 2 + $(document).scrollTop(),
                        left: ($(window).width() - 140) / 2 + $(document).scrollLeft()
                    }
                });
                if (objScreen.mrType == 1) {
                    return;
                }
                //更新状态
                var ax = new $ax("/sds/sdsqcformshow/changeMrStatus", function (data) {
                    objScreen.InitMrButtons();
                    //操作成功后  清除编辑值记录
                    // objScreen.EditItem = [];
                    // objScreen.EditVal = [];
                    objScreen.EditItemVal.clear();
                }, function (data) {
                    $.messager.alert("错误提示", "状态更新错误!", 'info');
                });
                ax.set('mrListId', objScreen.mrListId);
                ax.set('status', aCode);
                ax.set('execUser', $("#execUser").val())
                ax.set('execUserId', $("#execUserId").val())
                ax.set('reason', '');
                ax.set('resume', '');
                ax.set('msgDetailsId', $("msgDetailsId").val());
                //add   操作开始日期
                if (objScreen.EditItemVal.size == 0) {
                    //如果当次操作没有变更表单，则不记录开始编辑日期
                    ax.set('operStartTime', "");
                } else {
                    ax.set('operStartTime', objScreen.operStartTime);
                    ax.set('operEndTime', getNowFormatDate());
                }
                ax.start();

                // 如果满足下列条件：1.医生直接上报 2.合并上报 3.提交按钮
                if (objScreen.formCheckType == "Y" && objScreen.isMergeReport == "Y" && aCode == "Submit") {
                    // 提交和上报合并
                    objScreen.upReport("Up");
                }
            }
        }
    });
}

/**
 * 遍历锚点列表，分别计算各章节的必填项完成情况
 * @constructor
 */
objScreen.CalculateChapter = function () {
    $("#anchor li a").each(
        function (index, el) {
            var href = $(el).attr("href");
            var isNeededMap = $(href).next().find("[name='isNeeded']");
            var isNeededCnt = 0;
            var filledCnt = 0;
            isNeededMap.each(function (index, el2) {
                var rowId = $(el2).parent().parent().attr("id");
                if ($("#" + rowId).css("display") == 'none') {
                    return;
                }
                var itemId = rowId.replace("_Row", "");
                var tValue = Common_GetSDValue(itemId, $("#" + itemId)[0].className)
                if (tValue != "" && tValue != null) {
                    filledCnt++;
                }
                isNeededCnt++;
            })
            var cntHtml = "[" + filledCnt + "/" + isNeededCnt + "] ";
            $(el).prepend(cntHtml);
            // 如果有未填必填项，追加样式显示红色
            filledCnt != isNeededCnt ? $(el).addClass("unfinished") : $(el).removeClass("unfinished");
        })
}

/**
 * 计算当前项目所属章节的必填项完成情况
 * @param itemId
 * @constructor
 */
objScreen.CalculateCurrentChapter = function (curItemId) {
    var curRowId = curItemId + "_Row";
    var isNeededCnt = 0;
    var filledCnt = 0;
    $("#" + curRowId).parent().children("div").each(
        function (index, el) {
            var rowId = $(el).attr("id");
            if ($("#" + rowId).find("[name='isNeeded']").length == 0 || $("#" + rowId).css("display") == 'none') {
                return;
            }
            var itemId = rowId.replace("_Row", "");
            var tValue = Common_GetSDValue(itemId, $("#" + itemId)[0].className)
            if (tValue != "" && tValue != null) {
                filledCnt++;
            }
            isNeededCnt++;
        })
    var anchorId = $("#" + curRowId).parent().prev().attr("id");
    var anchorObj = $("#anchor li a[href=#" + anchorId + "]");
    var oldHtml = anchorObj.html();
    var titleHtml = oldHtml.split("]")[1];
    $(anchorObj).html("[" + filledCnt + "/" + isNeededCnt + "] " + titleHtml)
    // 如果有未填必填项，追加样式显示红色
    filledCnt != isNeededCnt ? $(anchorObj).addClass("unfinished") : $(anchorObj).removeClass("unfinished");
}
//校验整个表单项目的合法性
objScreen.valiForm = function (aitemcat) {
    var data = objScreen.formdata;
    var ValiMsg = "", count = 0;
    var ErrCat = new Array();
    var length = data.length;
    var ErrItem = new Array();
    for (var i = 0; i < length; i++) {
        var item = data[i];
        var itemId = item.id;
        var itemCode = item.btCode;
        var Value = item.execResult;
        var ItemCat = item.btItemCat;
        var itemType = $('#' + itemId)[0].className;
        var itemDesc = $('#' + itemId + '_Row').children().first()[0].innerText;

        //校验指定项目大类
        if ((aitemcat !== "") && (aitemcat != ItemCat)) continue;
        var RowCls = $('#' + itemId + '_Row').css('display');
        if (RowCls == 'none') continue;			//如果项目没展现，则不再校验
        var newValue = Common_GetSDValue(itemId, itemType);
        if (newValue == 'def') newValue = "";
        var noteText = $('#' + itemId + '_Note').text();
        if (noteText.indexOf('必填项') > -1) {		//如果有校验信息，则不再校验
            count = count + 1;
            ErrItem.push(itemId);
            if ($.inArray(ItemCat, ErrCat) == -1) ErrCat.push(ItemCat);
            continue;
        } else if (noteText != "") {
            var einfo = itemDesc + "-" + noteText;
            ValiMsg = ValiMsg + einfo + "<br>";
            ErrItem.push(itemId);
            if ($.inArray(ItemCat, ErrCat) == -1) ErrCat.push(ItemCat);
            continue;
        }

        if ((objScreen.initFlg == 1) && (newValue != "" && newValue != undefined)) {
            continue;
        } 		//如果已经全局校验过，有值的项目则不需要校验
        if ((newValue == "" || newValue == undefined) && (itemDesc.indexOf('*') > -1)) {
            var WarningInfo = "必填项不能为空";
            $('#' + itemId + '_Note').html('<span style="color:red">' + WarningInfo + '</span>');
            ErrItem.push(itemId);
        } else if ((Value != "") && (Value == newValue)) {
            //对没有进行过编辑，且有初始值的项目进行校验
            //对已经编辑过的项目，已经做了实时校验，这里不再统一校验
            objScreen.ValiItem(itemId, Value, itemType);
        }
        noteText = $('#' + itemId + '_Note').text();
        if (noteText.indexOf('必填项') > -1) {
            count = count + 1;
            ErrItem.push(itemId);
            if ($.inArray(ItemCat, ErrCat) == -1) ErrCat.push(ItemCat);
        } else if (noteText != "") {
            var einfo = itemDesc + "-" + noteText;
            ValiMsg = ValiMsg + einfo + "<br>";
            ErrItem.push(itemId);
            if ($.inArray(ItemCat, ErrCat) == -1) ErrCat.push(ItemCat);
        }
    }
    var needVali = "";
    if (count > 0) {
        needVali = '共 ' + count + ' 项必填项未填!<hr>';
    }
    ValiMsg = needVali + ValiMsg;
    if (aitemcat == "") {
        objScreen.initFlg = 1; //全局校验标记，防止多次校验影响网页速度
    } else {
        if (ValiMsg != "") {
            //对单个大类校验时，进行错误信息提示。
            $('div[title="' + aitemcat + '"]').prev().attr({'errorInfo': " (" + ValiMsg.replace(/<\/?.+?>/g, "").replace(/ /g, "") + ")"});
        }
    }
    //标记已经完成和有填报错误的大类
    if (aitemcat != "") {
        if ($.inArray(aitemcat, ErrCat) > -1) {
            $('div[title="' + aitemcat + '"]').prev().css({'color': 'red'});
        } else {
            $('div[title="' + aitemcat + '"]').prev().css({'color': 'green'});
        }
    } else {
        for (var i = 0; i < objScreen.validCat.length; i++) {
            var xitemCat = objScreen.validCat[i];
            $('div[title="' + xitemCat + '"]').prev().attr({'errorInfo': ''});
            if ($.inArray(xitemCat, ErrCat) > -1) {
                $('div[title="' + xitemCat + '"]').prev().css({'color': 'red'});
            } else {
                $('div[title="' + xitemCat + '"]').prev().css({'color': 'green'});
                $('div[title="' + xitemCat + '"]').css({'display': 'none'});
                $('div[title="' + xitemCat + '"]').prev().addClass('itemCat-fold');
            }
        }
    }
    // 自动定位到第一个错误项目位置
    if (ErrItem.length != 0) {
        $("#" + ErrItem[0] + "_Row")[0].scrollIntoView();
    }

    return ValiMsg;
}
objScreen.UpdateStatus = function (sCode) {
    if (sCode == "") return;
    var SDesc = (sCode == "Check" ? "审核" : sCode == "Submit" ? "取消审核" : sCode == "Up" ? "上传" : sCode == "O" ? "排除" : sCode == "Back" ? "退回" : 1)
    $.messager.confirm("提示", "是否" + SDesc + "这份病例?", function (r) {
        if (r) {
            if (sCode == "O") {
                //打开 弹出框
                var index = layer.open({
                    type: 2,
                    title: ['排除单病种【信息录入】'],
                    area: ['600px', '400px'],
                    zIndex: 19911102,//这是个大坑！！！！ 默认是19891014 远远大于量表下拉框的zIndex 导致下拉框的数据看不到！！！
                    content: "/sds/sdsqcformshow/excludereason?mrListId=" + objScreen.mrListId + "&entityId=" + objScreen.entityId + "&execUser=" + encodeURIComponent($("#execUser").val()),
                    skin: 'layer-ext-hisui',
                    scrollbar: false//为了禁止父页面滚动条滚动
                });
                this.layerIndex = index;

                //监听子页面的postMessage
                function receiveMessage(event) {
                    //取得子页面传回来的值
                    if (event.data == "close") {
                        // 如果传回close，关闭当前弹窗
                        layer.close(index);
                    }
                    if (event.data == "save") {
                        // objScreen.InitMrButtons();
                        setTimeout(function () {
                            layer.close(index);
                            if (typeof SdsQcincase2 !== 'undefined') {
                                SdsQcincase2.table.refresh();
                            }
                            if (typeof SdsFillByDoctor !== 'undefined') {
                                SdsFillByDoctor.table.refresh();
                            }
                            $("#p1").empty();
                        }, 1000);
                    }
                }

                if (window.addEventListener) {
                    // 在现代浏览器中使用addEventListener
                    window.addEventListener('message', receiveMessage, false);
                } else if (window.attachEvent) {
                    // 在IE8及以下版本中使用attachEvent
                    window.attachEvent('onmessage', receiveMessage);
                }

            } else if (sCode == "Back") {
                //退回报告需要填写退回原因
                $.messager.prompt("提示", "请输入退回原因：", function (r) {
                    if (r) {
                        //提交信息
                        var ajax = new $ax("/sds/sdsqcformshow/changeMrStatus", function (data) {
                            $.messager.popover({
                                msg: SDesc + '操作成功！',
                                type: 'success',
                                timeout: 1000,
                                style: {
                                    top: ($(window).height() - 50) / 2 + $(document).scrollTop(),
                                    left: ($(window).width() - 140) / 2 + $(document).scrollLeft()
                                }
                            })
                            // objScreen.InitMrButtons();
                            setTimeout(function () {
                                if (typeof SdsQcincase2 !== 'undefined') {
                                    SdsQcincase2.table.refresh();
                                }
                                if (typeof SdsFillByDoctor !== 'undefined') {
                                    SdsFillByDoctor.table.refresh();
                                }
                                $("#p1").empty();
                            }, 1000);
                        }, function (data) {
                            $.messager.alert("错误提示", "状态更新错误!", 'info');
                        });
                        ajax.set('mrListId', objScreen.mrListId);
                        ajax.set('status', sCode);
                        ajax.set('execUser', $("#execUser").val())
                        ajax.set('reason', '');
                        ajax.set('resume', r);
                        ajax.set('msgDetailsId', $("msgDetailsId").val());
                        ajax.start();
                    } else {
                        $.messager.popover({
                            msg: "您撤销了退回操作！",
                            type: 'info',
                            style: {
                                top: ($(window).height() - 50) / 2 + $(document).scrollTop(),
                                left: ($(window).width() - 140) / 2 + $(document).scrollLeft()
                            }
                        });
                    }
                });
            } else {
                //提交信息
                var ajax = new $ax("/sds/sdsqcformshow/changeMrStatus", function (data) {
                    $.messager.popover({
                        msg: SDesc + '操作成功！',
                        type: 'success',
                        timeout: 1000,
                        style: {
                            top: ($(window).height() - 50) / 2 + $(document).scrollTop(),
                            left: ($(window).width() - 140) / 2 + $(document).scrollLeft()
                        }
                    })
                    setTimeout(function () {
                        if (typeof SdsQcincase2 !== 'undefined') {
                            SdsQcincase2.table.refresh();
                        }
                        if (typeof SdsFillByDoctor !== 'undefined') {
                            SdsFillByDoctor.table.refresh();
                        }
                        $("#p1").empty();
                    }, 1000);
                }, function (data) {
                    $.messager.alert("错误提示", "状态更新错误!", 'info');
                });
                ajax.set('mrListId', objScreen.mrListId);
                ajax.set('status', sCode);
                ajax.set('execUser', $("#execUser").val())
                ajax.set('reason', '');
                ajax.set('resume', '');
                ajax.set('msgDetailsId', $("msgDetailsId").val());
                ajax.start();

                // 如果满足下列条件：1.审核环节 2.合并上报 3.审核按钮
                if (objScreen.formCheckType == "N" && objScreen.isMergeReport == "Y" && sCode == "Check") {
                    // 审核和上报合并
                    objScreen.upReport("Up");
                }
            }
        }
    });
}
objScreen.fireEvent = function (ItemId, Value) {
    //触发项目变更时，自动展现各级关联项目去重处理，防止项目嵌套导致无限循环展现
    autoShowedCodeArr = new Array()
    if (objScreen.addListener == 0) {
        return false;
    } else {
        var itemCode = $("#" + ItemId).attr("itemCode");
        var itemType = $('#' + ItemId)[0].className;
        if ((Value == "") || (Value == undefined)) {
            //列表值变化没有传入值，取列表值
            Value = Common_GetSDValue(ItemId, itemType);
        }
        //将编辑过的值存储起来，方便后面存储
        if (objScreen.EditItemVal.has(ItemId)) {
            objScreen.EditItemVal.del(ItemId);
        }
        objScreen.EditItemVal.set(ItemId, Value);

        //根据该项目值判断相关联项目的展现/隐藏属性
        objScreen.autoShowItem(ItemId, itemCode);
        //对该项目合法性进行校验
        objScreen.ValiItem(ItemId, Value, itemType);
        //与该项目有关的自动赋值
        objScreen.LoadSubItemDicFront(ItemId);
        //计算当前章节的必填项情况
        objScreen.CalculateCurrentChapter(ItemId);
        //获取需要实时计算的值
        objScreen.getRealTimeItem(itemCode);
    }
}
//展现/隐藏项目
objScreen.autoShowItem = function (curItemId, curItemCode) {
    autoShowedCodeArr[curItemCode] = true
    //根据该项目Code获取被关联项目的展现/隐藏属性
    var relativeItem = [];
    // 后台进行项目校验并返回错误信息
    var ajax = new $ax("/sds/sdsqcformshow/triggerLinkItem", function (data) {
        relativeItem = data;
    });
    var param = {};
    param.entityId = objScreen.entityId;
    param.formItemId = curItemId;
    param.formItemCode = curItemCode;
    ajax.setData(param);
    ajax.start();

    // 如果没有关联此项的项目，退出；
    if (relativeItem.length == 0) {
        return;
    }
    for (var i = 0, rl = relativeItem.length; i < rl; i++) {
        var relItem = relativeItem[i];
        if (relItem == "") continue;
        var linkItemArr = relItem.linkItem;
        for (var j = 0, l = linkItemArr.length; j < l; j++) {
            var linkItem = linkItemArr[j];
            if (linkItem == "") continue;
            var linkId = linkItem.itemId;
            var linkVal = Common_GetSDValue(linkId, $('#' + linkId)[0].className);
            // 如果项目被隐藏，取值为空
            if ($('#' + linkId + '_Row').css('display') == 'none') linkVal = "";
            linkItem['itemVal'] = linkVal;
            linkItemArr[j] = linkItem;
        }
        relativeItem[i].linkItem = linkItemArr;
    }
    ;

    var MsgArr = [];
    // 后台进行项目校验并返回错误信息
    var ax = new $ax("/sds/sdsqcformshow/linkItemMsg", function (data) {
        MsgArr = data;
    });
    var param = {};
    param.entityId = objScreen.entityId;
    param.formItemId = curItemId;
    param.formItemLink = encodeURIComponent(JSON.stringify(relativeItem));
    ax.setData(param);
    ax.start();
    for (var m = 0, ml = MsgArr.length; m < ml; m++) {
        var item = MsgArr[m];
        var itemId = item.itemId;
        var itemCode = item.itemCode;
        var EditPower = item.showFlg;
        if ((itemId == "") || (itemId == undefined)) continue;
        if (EditPower == 1) {
            var initFlg = $('#' + itemId).attr("InitFlg");
            var initVal = $('#' + itemId).attr("InitVal");
            var initText = $('#' + itemId).attr("InitText");
            if (itemId != curItemId && initFlg != 1) {
                var itemClass = $("#" + itemId)[0].className;
                if (itemClass.indexOf('Combo') > -1) {
                    var multi = false;
                    if (itemClass.indexOf('mul') > -1) multi = true;
                    objScreen.CreatCombo(itemId, multi);
                    $('#' + itemId).combobox('setValue', initVal, initText);
                } else if (itemClass == 'RadioGroup') {
                    Common_RadioToSDDic(itemId, itemId);
                    //给单选列表赋值
                    $('[name="' + itemId + '"][value="' + initVal + '"]').radio('setValue', true);
                } else if (itemClass == 'CheckGroup') {
                    Common_CheckboxToSDDic(itemId, itemId, 1);
                    if (initVal) {
                        var valArr = initVal.split(',');
                        //循环给多选列表赋值
                        for (var j = 0; j < valArr.length; j++) {
                            if (valArr[j] == "") continue;
                            $('[name=' + itemId + '][value=' + valArr[j] + ']').radio('setValue', true);
                        }
                    }
                } else {
                    $('#' + itemId).val(initVal);
                }
                // 标记该项目已渲染
                $('#' + itemId).attr("InitFlg", 1);
                // 将再次显示的项目值添加到编辑集合中
                objScreen.EditItemVal.set(itemId, initVal);
            }
            $('#' + itemId + "_Row").show()
            //判断子标题是否需要显示
            if ($('#' + itemId + "_Row").prev()[0].className == 'itemsubCat') {
                $('#' + itemId + "_Row").prev().show();
            }
            //如果子项的值不为空，则继续判断其子项是否展现
            var tValue = Common_GetSDValue(itemId, $("#" + itemId)[0].className)
            if ((tValue != "") && (!autoShowedCodeArr[itemCode])) {
                objScreen.autoShowItem(itemId, itemCode)
            } else {
                autoShowedCodeArr[itemCode] = true
            }
        } else {
            if (autoShowedCodeArr[itemCode]) {
                continue
            }
            $('#' + itemId + "_Row").hide();
            //判断子标题是否需要隐藏
            if ($('#' + itemId + "_Row").prev()[0].className == 'itemsubCat') {
                $('#' + itemId + "_Row").prev().hide();
            }
            // 删除隐藏项的编辑记录
            objScreen.EditItemVal.del(itemId);
        }
        //计算当前章节的必填项情况
        objScreen.CalculateCurrentChapter(itemId);
    }
}
//对该项目进行校验
objScreen.ValiItem = function (ItemId, ItemValue, ItemType) {
    if (ItemValue == undefined) {
        ItemValue = "";
    }
    //清空历史信息，准备显示最新的校验信息
    $('#' + ItemId + '_Note').html('');
    if ((ItemValue == "" || ItemValue == undefined) && ($('#' + ItemId + '_Row')[0].innerText.indexOf('*') > -1)) {
        var WarningInfo = "必填项不能为空"
        $('#' + ItemId + '_Note').html('<span style="color:red">' + WarningInfo + '</span>');
        return
    }
    var RuleItemIdArr = [];
    // 获取当前项目检验规则涉及到的项目，以便取值计算
    var ax = new $ax("/sds/sdsqcformshow/ruleLinkItem", function (data) {
        RuleItemIdArr = data;
    });
    ax.set("entityId", objScreen.entityId);
    ax.set("formItemId", ItemId);
    ax.start();

    var LinkItemObj = [];
    for (var i = 0, l = RuleItemIdArr.length; i < l; i++) {
        var RIdi = RuleItemIdArr[i];
        if (RIdi == "") continue;
        var RValuei = Common_GetSDValue(RIdi.itemId, ItemType);
        LinkItemObj.push({'itemId': RIdi.itemId, 'itemCode': RIdi.itemCode, 'itemVal': RValuei});
    }
    ;

    var MsgArr = [];
    // 后台进行项目校验并返回错误信息
    var ajax = new $ax("/sds/sdsqcformshow/validMsg", function (data) {
        MsgArr = data;
    });
    var param = {};
    param.entityId = objScreen.entityId;
    param.formItemId = ItemId;
    param.formItemCode = $("#" + ItemId).attr("itemCode");
    param.formItemValue = ItemValue;
    param.formItemType = ItemType;
    param.formItemLink = JSON.stringify(LinkItemObj);
    ajax.setData(param);
    ajax.start();

    for (var j = 0, l = MsgArr.length; j < l; j++) {
        var Msg = MsgArr[j];
        var msgType = Msg.msgType;
        var msgContent = Msg.msgContent;
        if (msgType == 'Stop') {
            $.messager.confirm("提示", msgContent + ",是否退出并排除这份病例?", function (r) {
                if (r) {
                    objScreen.UpdateStatus('O');
                    return;
                }
            })
            // 重置当前选择项
            if (ItemType == "RadioGroup") {
                $('[name=' + ItemId + '][value=' + ItemValue + ']').radio('setValue', false);
            } else if (ItemType == "CheckGroup") {
                $('[name=' + ItemId + '][value=' + ItemValue + ']').radio('setValue', false);
            } else if (ItemType.indexOf("Combo") > -1) {
                $("#" + ItemId).combobox("setValue", null);
            }
        } else if (msgType == 'Error') {
            $('#' + ItemId + '_Note').append('<span style="color:#ff0000">' + msgContent + '</span><br/>')
        } else {
            $('#' + ItemId + '_Note').append('<span style="color:#40A2DE;">' + msgContent + '</span><br/>')
        }
    }
}

objScreen.LoadSubItemDic = function (itemId) {
    var itemCode = $("#" + itemId).attr("itemCode");
    ///加载关联项目逻辑值
    var relativeItem = [];
    var ax = new $ax("/sds/sdsqcformshow/GetLogicLinkItem", function (data) {
        relativeItem = data;
    });
    ax.set("entityId", objScreen.entityId);
    ax.set("formItemId", itemId);
    ax.set("formItemCode", itemCode);
    ax.start();

    // 如果没有关联此项的项目，退出；
    if (relativeItem.length == 0) {
        return;
    }
    for (var i = 0, rl = relativeItem.length; i < rl; i++) {
        var relItem = relativeItem[i];
        if (relItem == "") continue;
        var linkItemArr = relItem.expItems;
        for (var j = 0, l = linkItemArr.length; j < l; j++) {
            var linkItem = linkItemArr[j];
            if (linkItem == "") continue;
            var linkId = linkItem.itemId;
            var linkVal = Common_GetSDValue(linkId, $('#' + linkId)[0].className);
            linkItem['itemVal'] = linkVal;
            linkItemArr[j] = linkItem;
        }
        relativeItem[i].linkItem = linkItemArr;
    }

    //获取关联项目值并赋值
    var obj = {};
    // 后台进行项目校验并返回错误信息
    var ax = new $ax("/sds/sdsqcformshow/GetLinkItemDefaultVal", function (data) {
        obj = data;
    });
    var param = {};
    param.entityId = objScreen.entityId;
    param.formItemId = itemId;
    param.formItemLink = encodeURIComponent(JSON.stringify(relativeItem));
    ax.setData(param);
    ax.start();

    for (var key in obj) {
        var itemVal = obj[key];
        var itemclass = $('#' + key)[0].className
        if (itemclass.indexOf('Combo') > -1) {
            var multi = false
            if (itemclass.indexOf('mul') > -1) multi = true
            objScreen.CreatCombo(key, multi);
            $('#' + key).combobox('setValue', itemVal, "")
        } else if (itemclass == 'RadioGroup') {
            Common_RadioToSDDic(key, key);
            //给单选列表赋值
            $('[name="' + key + '"][value="' + itemVal + '"]').radio('setValue', true)
        } else if (itemclass == 'CheckGroup') {
            Common_CheckboxToSDDic(key, key, 1);
            var valArr = itemVal.split(',')
            //循环给多选列表赋值
            for (var j = 0; j < valArr.length; j++) {
                if (valArr[j] == "") continue;
                $('[name=' + key + '][value=' + valArr[j] + ']').radio('setValue', true);
            }
        } else {
            $('#' + key).val(itemVal)
        }
        // 记录该项目是否被渲染过
        $('#' + key).attr("InitFlg", 1);

        objScreen.fireEvent(key, itemVal);
    }
}

objScreen.LoadSubItemDicFront = function (itemId) {
    var itemCode = $("#" + itemId).attr("itemCode");
    ///加载关联项目逻辑值
    var relativeItem = [];
    var ax = new $ax("/sds/sdsqcformshow/GetLogicLinkItem", function (data) {
        relativeItem = data;
    });
    ax.set("entityId", objScreen.entityId);
    ax.set("formItemId", itemId);
    ax.set("formItemCode", itemCode);
    ax.start();

    // 如果没有关联此项的项目，退出；
    if (relativeItem.length == 0) {
        return;
    }
    var itemMap = new Map();
    for (var i = 0, rl = relativeItem.length; i < rl; i++) {
        var relItem = relativeItem[i];
        if (relItem == "") continue;
        var subItemId = relItem.itemId;
        var subItemType = $('#' + subItemId)[0].className;
        var subDicCode = relItem.itemDicCode;
        var subDicExp = relItem.calcExp;
        var linkItemArr = relItem.expItems;
        for (var j = 0, l = linkItemArr.length; j < l; j++) {
            var linkItem = linkItemArr[j];
            if (linkItem == "") continue;
            var linkId = linkItem.itemId;
            var linkVal = Common_GetSDValue(linkId, $('#' + linkId)[0].className);
            linkItem['itemVal'] = linkVal;
            linkItemArr[j] = linkItem;
        }
        if (!itemMap.has(subItemId)) {
            itemMap.set(subItemId, "");
        }
        var result = calcExp(subDicExp, linkItemArr)
        var val = itemMap.get(subItemId);
        if (result == 1) {
            if (subItemType.indexOf('CheckGroup') > -1) {
                val += subDicCode + ",";
            } else {
                val = subDicCode;
            }
        }
        if (val != "") {
            itemMap.del(subItemId);
            itemMap.set(subItemId, val);
        }
    }

    itemMap.forEach(function (itemVal, key, itemMap) {
        var itemclass = $('#' + key)[0].className;
        if (itemclass.indexOf('Combo') > -1) {
            var multi = false
            if (itemclass.indexOf('mul') > -1) multi = true
            objScreen.CreatCombo(key, multi);
            $('#' + key).combobox('setValue', itemVal, "")
        } else if (itemclass == 'RadioGroup') {
            Common_RadioToSDDic(key, key);
            //给单选列表赋值
            $('[name="' + key + '"][value="' + itemVal + '"]').radio('setValue', true)
        } else if (itemclass == 'CheckGroup') {
            Common_CheckboxToSDDic(key, key, 1);
            var valArr = itemVal.split(',')
            //循环给多选列表赋值
            for (var j = 0; j < valArr.length; j++) {
                if (valArr[j] == "") continue;
                $('[name=' + key + '][value=' + valArr[j] + ']').radio('setValue', true);
            }
        } else {
            $('#' + key).val(itemVal)
        }
        // 记录该项目是否被渲染过
        $('#' + key).attr("InitFlg", 1);

        objScreen.fireEvent(key, itemVal);
    })
}

objScreen.getRealTimeItem = function (curItemCode) {
    //加载关联项目逻辑值
    var relativeItem = [];
    
    var ajax = new $ax("/sds/sdsqcformshow/getRealTimeItem", function (data) {
        relativeItem = data;
    });
    var param = {};
    param.entityId = objScreen.entityId;
    param.formItemCode = curItemCode;
    ajax.setData(param);
    ajax.start();

    // 如果没有关联此项的项目，退出；
    if (relativeItem.length == 0) {
        return;
    }
    for (var i = 0, rl = relativeItem.length; i < rl; i++) {
        var relItem = relativeItem[i];
        if (relItem == "") continue;
        var subItemId = relItem.itemId;
        var subDicExp = relItem.calcExp;
        var linkItemArr = relItem.expItems;
        for (var j = 0, l = linkItemArr.length; j < l; j++) {
            var linkItem = linkItemArr[j];
            if (linkItem == "") continue;
            var linkId = linkItem.itemId;
            var linkVal = Common_GetSDValue(linkId, $('#' + linkId)[0].className);
            linkItem['itemVal'] = linkVal;
            linkItemArr[j] = linkItem;
        }
        if (subDicExp.startsWith('REAL-TIME-ROBSON')) {
            // Robson分类法组别实时判断
            var itemVal = getRobson(linkItemArr);
            $('#' + subItemId).combobox('setValue', itemVal, "")
        } else {
            var itemVal = calcLinkExp(subDicExp, linkItemArr);
            $('#' + subItemId).val(itemVal)
        }
        // 记录该项目是否被渲染过
        $('#' + subItemId).attr("InitFlg", 1);

        objScreen.fireEvent(subItemId, itemVal);
    }
}

function RobsonGroup() {
    // CS-1-1-1:产次; CS-1-1-8:有无剖宮产史; CS-1-1-3:临产方式; CS-1-1-4:孕周; CS-1-1-5:胎位; CS-1-1-6:胎儿数量
    return [
        {
            'value': 'a',
            'name': '1组(NS)=初产+单胎+足月+自然临产',
            'condition': [
                {
                    'code': 'CS-1-1-1',
                    'value': 'y'
                },
                {
                    'code': 'CS-1-1-6',
                    'value': 'a'
                },
                {
                    'code': 'CS-1-1-4',
                    'value': 'b'
                },
                {
                    'code': 'CS-1-1-3',
                    'value': 'a'
                }
            ]
        },
        {
            'value': 'b',
            'name': '2A组(N1)=初产+单胎+足月+引产临产',
            'condition': [
                {
                    'code': 'CS-1-1-1',
                    'value': 'y'
                },
                {
                    'code': 'CS-1-1-6',
                    'value': 'a'
                },
                {
                    'code': 'CS-1-1-4',
                    'value': 'b'
                },
                {
                    'code': 'CS-1-1-3',
                    'value': 'b'
                }
            ]
        },
        {
            'value': 'c',
            'name': '2B组(NC)=初产+单胎+足月+临产前剖宫产',
            'condition': [
                {
                    'code': 'CS-1-1-1',
                    'value': 'y'
                },
                {
                    'code': 'CS-1-1-6',
                    'value': 'a'
                },
                {
                    'code': 'CS-1-1-4',
                    'value': 'b'
                },
                {
                    'code': 'CS-1-1-3',
                    'value': 'c'
                }
            ]
        },
        {
            'value': 'd',
            'name': '3组(MS)=经产+单胎+足月+无剖宫产史+自然临产',
            'condition': [
                {
                    'code': 'CS-1-1-1',
                    'value': 'n'
                },
                {
                    'code': 'CS-1-1-6',
                    'value': 'a'
                },
                {
                    'code': 'CS-1-1-4',
                    'value': 'b'
                },
                {
                    'code': 'CS-1-1-8',
                    'value': 'c'
                },
                {
                    'code': 'CS-1-1-3',
                    'value': 'a'
                }
            ]
        },
        {
            'value': 'e',
            'name': '4A组(M1)=经产+单胎+足月+无剖宫产史+引产临产',
            'condition': [
                {
                    'code': 'CS-1-1-1',
                    'value': 'n'
                },
                {
                    'code': 'CS-1-1-6',
                    'value': 'a'
                },
                {
                    'code': 'CS-1-1-4',
                    'value': 'b'
                },
                {
                    'code': 'CS-1-1-8',
                    'value': 'c'
                },
                {
                    'code': 'CS-1-1-3',
                    'value': 'b'
                }
            ]
        },
        {
            'value': 'f',
            'name': '4B组(MC)=经产+单胎+足月+无剖宫产史+临产前剖宫产',
            'condition': [
                {
                    'code': 'CS-1-1-1',
                    'value': 'n'
                },
                {
                    'code': 'CS-1-1-6',
                    'value': 'a'
                },
                {
                    'code': 'CS-1-1-4',
                    'value': 'b'
                },
                {
                    'code': 'CS-1-1-8',
                    'value': 'c'
                },
                {
                    'code': 'CS-1-1-3',
                    'value': 'c'
                }
            ]
        },
        {
            'value': 'g',
            'name': '5A组(PC1)=经产+单胎+足月+头位+只有一次剖宫产史',
            'condition': [
                {
                    'code': 'CS-1-1-1',
                    'value': 'n'
                },
                {
                    'code': 'CS-1-1-6',
                    'value': 'a'
                },
                {
                    'code': 'CS-1-1-4',
                    'value': 'b'
                },
                {
                    'code': 'CS-1-1-5',
                    'value': 'a'
                },
                {
                    'code': 'CS-1-1-8',
                    'value': 'a'
                }
            ]
        },
        {
            'value': 'h',
            'name': '5B组(PC2)=经产+单胎+足月+头位+有2次及以上剖宫产史',
            'condition': [
                {
                    'code': 'CS-1-1-1',
                    'value': 'n'
                },
                {
                    'code': 'CS-1-1-6',
                    'value': 'a'
                },
                {
                    'code': 'CS-1-1-4',
                    'value': 'b'
                },
                {
                    'code': 'CS-1-1-5',
                    'value': 'a'
                },
                {
                    'code': 'CS-1-1-8',
                    'value': 'b'
                }
            ]
        },
        {
            'value': 'i',
            'name': '6组(BR)=初产+单胎+臀位',
            'condition': [
                {
                    'code': 'CS-1-1-1',
                    'value': 'y'
                },
                {
                    'code': 'CS-1-1-6',
                    'value': 'a'
                },
                {
                    'code': 'CS-1-1-5',
                    'value': 'b'
                }
            ]
        },
        {
            'value': 'j',
            'name': '7组(BR)=经产+单胎+臀位+有剖宫产史',
            'condition': [
                {
                    'code': 'CS-1-1-1',
                    'value': 'n'
                },
                {
                    'code': 'CS-1-1-6',
                    'value': 'a'
                },
                {
                    'code': 'CS-1-1-5',
                    'value': 'b'
                },
                {
                    'code': 'CS-1-1-8',
                    'value': ['a', 'b']
                }
            ]
        },
        {
            'value': 'k',
            'name': '8组(TW)=初产或经产+多胎',
            'condition': [
                {
                    'code': 'CS-1-1-1',
                    'value': ['y', 'n']
                },
                {
                    'code': 'CS-1-1-6',
                    'value': 'b'
                }
            ]
        },
        {
            'value': 'l',
            'name': '9组(BR)=初产或经产+单胎+横位',
            'condition': [
                {
                    'code': 'CS-1-1-1',
                    'value': ['y', 'n']
                },
                {
                    'code': 'CS-1-1-6',
                    'value': 'a'
                },
                {
                    'code': 'CS-1-1-5',
                    'value': 'c'
                }
            ]
        },
        {
            'value': 'm',
            'name': '10组(PT)=初产或经产+早产+单胎+头位',
            'condition': [
                {
                    'code': 'CS-1-1-1',
                    'value': ['y', 'n']
                },
                {
                    'code': 'CS-1-1-4',
                    'value': 'a'
                },
                {
                    'code': 'CS-1-1-6',
                    'value': 'a'
                },
                {
                    'code': 'CS-1-1-5',
                    'value': 'a'
                }
            ]
        },
        {
            'value': 'n',
            'name': '11组(UK)=所有因数据不全而无法分类的产妇',
            'condition': []
        }
    ]
}

function getRobson(linkItemArr) {
    var robsonGroup = RobsonGroup();
    for (var i = 0; i < robsonGroup.length; i++) {
        var conditions = robsonGroup[i]['condition'];
        var flag = 1;
        for (var j = 0; j < conditions.length; j++) {
            var condition = conditions[j];
            for (var k = 0; k < linkItemArr.length; k++) {
                var item = linkItemArr[k];
                var itemCode = item.itemCode;
                var itemVal = item.itemVal;
                if (itemCode == condition.code) {
                    var val = condition.value;
                    if (typeof val === 'string') {
                        if (val != itemVal) {
                            flag = 0;
                            break;
                        }
                    } else if (Array.isArray(val)) {
                        if (val.indexOf(itemVal) == -1) {
                            flag = 0;
                            break;
                        }
                    } else {
                        flag = 0;
                        break;
                    }
                }
            }
        }
        if (flag == 1) {
            return robsonGroup[i].value;
        }
    }
    return 'n';
}

function calcLinkExp(expStr, linkItemArr) {
    var result = "";
    var regex_b = /{(.+?)}/g; // 大花括号
    // 替换表达式中值
    for (var j = 0; j < linkItemArr.length; j++) {
        var linkItem = linkItemArr[j];
        var subItem = linkItem.itemCode;
        var subVal = linkItem.itemVal;
        if (subVal == '') {
            return result;
        }
        subVal = "'" + subVal + "'";
        expStr = customReplaceAll(expStr, subItem, subVal);
    }

    if (expStr.match(regex_b)) { //如果包含大括号
        var subExpArr = expStr.match(regex_b);
        for (var i = 0; i < subExpArr.length; i++) {
            var subExpStr = subExpArr[i].substring(1, subExpArr[i].length - 1);
            var subExpStr_new = parseExp(subExpStr);
            expStr = expStr.replace(subExpStr, subExpStr_new);
        }
    } else {//不包含大括号
        expStr = parseExp(expStr);
    }
    expStr = customReplaceAll(expStr, ":", "");
    // 将表达式中的大括号中括号替换为小括号，以及其他其他字符替换为可执行字符
    expStr = customReplaceAll(expStr, "{", "(");
    expStr = customReplaceAll(expStr, "}", ")");
    expStr = customReplaceAll(expStr, "[", "(");
    expStr = customReplaceAll(expStr, "]", ")");
    expStr = expStr.replace(/\.contains\(([^)]+)\)/g, '.indexOf($1) !== -1');
    expStr = customReplaceAll(expStr, "indexOf(\"\")", "indexOf(\",,\")");
    expStr = customReplaceAll(expStr, "oth", "OTH");
    expStr = customReplaceAll(expStr, "def", "DEF");
    var res = eval(expStr);
    if (res) {
        res = parseFloat(res.toFixed(2));
        result = res;
    }
    return result;
}

function calcExp(expStr, linkItemArr) {
    var result = 0;
    var regex_b = /{(.+?)}/g; // 大花括号
    // 替换表达式中值
    for (var j = 0; j < linkItemArr.length; j++) {
        var linkItem = linkItemArr[j];
        var subItem = linkItem.itemCode;
        var subVal = linkItem.itemVal;
        if (subVal == '') {
            return result;
        }
        subVal = "'" + subVal + "'";
        expStr = customReplaceAll(expStr, subItem, subVal);
    }

    if (expStr.match(regex_b)) { //如果包含大括号
        var subExpArr = expStr.match(regex_b);
        for (var i = 0; i < subExpArr.length; i++) {
            var subExpStr = subExpArr[i].substring(1, subExpArr[i].length - 1);
            var subExpStr_new = parseExp(subExpStr);
            expStr = expStr.replace(subExpStr, subExpStr_new);
        }
    } else {//不包含大括号
        expStr = parseExp(expStr);
    }
    expStr = customReplaceAll(expStr, ":", "");
    // 将表达式中的大括号中括号替换为小括号，以及其他其他字符替换为可执行字符
    expStr = customReplaceAll(expStr, "{", "(");
    expStr = customReplaceAll(expStr, "}", ")");
    expStr = customReplaceAll(expStr, "[", "(");
    expStr = customReplaceAll(expStr, "]", ")");
    expStr = expStr.replace(/\.contains\(([^)]+)\)/g, '.indexOf($1) !== -1');
    expStr = customReplaceAll(expStr, "indexOf(\"\")", "indexOf(\",,\")");
    expStr = customReplaceAll(expStr, "oth", "OTH");
    expStr = customReplaceAll(expStr, "def", "DEF");
    if (eval(expStr)) {
        result = 1;
    }
    return result;
}

function parseExp(expStr) {
    var regex_s = /\((.+?)\)/g; // 小括号
    var regex = /([^:]+):(.+)/;
    var matches = regex.exec(expStr);
    var subExpType_l = "";
    var subExp_l = "";
    if (matches) {
        subExpType_l = matches[1].trim();
        subExp_l = matches[2].trim();
    }
    var divisor = 1;
    if (subExpType_l.indexOf("CALC") > -1) {
        if (subExpType_l == "CALC-h") {
            // 1小时毫秒数
            divisor = 60 * 60 * 1000;
        } else if (subExpType_l == "CALC-m") {
            // 一分钟毫秒数
            divisor = 60 * 1000;
        } else if (subExpType_l == "CALC-m") {
            // 一分钟毫秒数
            divisor = 60 * 1000;
        } else if (subExpType_l == "CALC-day") {
            // 一天毫秒数
            divisor = 24 * 60 * 60 * 1000;
        } else if (subExpType_l == "CALC-month") {
            // 一个月毫秒数
            divisor = 30 * 24 * 60 * 60 * 1000;
        } else if (subExpType_l == "CALC-year") {
            // 一年毫秒数
            divisor = 12 * 30 * 24 * 60 * 60 * 1000;
        }
        var subExpArr = subExp_l.match(regex_s)
        var exeExp = subExp_l;
        if (subExpArr) {
            for (var i = 0; i < subExpArr.length; i++) {
                var itemVal = subExpArr[i].substring(1, subExpArr[i].length - 1);
                itemVal = customReplaceAll(itemVal, "'", "");
                var itemVal_t = itemVal.replace(new RegExp(/-/gm), "/"); //转换 IE不支持new Date('2018-11-14 00:00:00')
                itemVal_t = new Date(itemVal_t).getTime();
                itemVal_t = Math.round(itemVal_t / divisor);
                exeExp = customReplaceAll(exeExp, itemVal, itemVal_t);
            }
        }
        expStr = expStr.replace(subExp_l, exeExp);
    }
    expStr = expStr.replace(subExpType_l, "");
    return expStr;
}

// 自定义替换函数以实现在IE中的替换操作
function customReplaceAll(str, find, replace) {
    return str.split(find).join(replace);
}


objScreen.CreatCombo = function (itemId, multi) {
    var dicArr = JSON.parse($("#" + itemId + "_Row").attr("dic"));

    $HUI.combobox("#" + itemId, {
        editable: true,
        defaultFilter: 4,
        allowNull: true,
        enterNullValueClear: true,
        blurValidValue: true,
        width: $(".itemCat").outerWidth() * 0.35, //$(".itemTR div").outerWidth(),
        multiple: multi,
        valueField: 'code',
        textField: 'desc',
        data: dicArr,
        // url: "/sds/sdsqcformshow/itemDics/" + itemId,
        onShowPanel: function () {
        },
        onSelect: function (rec) {
            if (multi) { ///父页面中直接打开dialog Combobox多选会有问题
                var comboData = $(this).combobox('getValues')
                $(this).combobox('getValues').forEach(function (element, index) {
                    if (!element) comboData.splice(index, 1)
                });
                $(this).combobox('setValues', comboData)
                objScreen.fireEvent(itemId, '');
            } else {
                objScreen.fireEvent(itemId, rec.code)
            }
        },
        onUnselect: function (rec) {
            if (multi) { ///父页面中直接打开dialog Combobox多选会有问题
                var comboData = $(this).combobox('getValues')
                $(this).combobox('getValues').forEach(function (element, index) {
                    if (!element) comboData.splice(index, 1)
                });
                $(this).combobox('setValues', comboData)
                objScreen.fireEvent(itemId, '');
            } else {
                objScreen.fireEvent(itemId, rec.code)
            }
        },
        onLoadSuccess: function () {
            //combobox会生成一个class为textbox-text validatebox-text textox-prompt的 text
            $(".combo-text").mouseover(function () {
                // 如果有配置启用显示数据源的功能，则给下拉框增加hover显示
                if (objScreen.isShowSourceData == 'Y') {
                    $(this).popover({
                        type: 'async',
                        url: '/sds/sdsqcformshow/getItemSourceDetail?mrListId=' + objScreen.mrListId + "&formItemId=" + itemId,
                        content: function (data) {
                            return data.message;
                        },
                        trigger: 'hover',
                        width: '500px',
                        placement: 'auto-right'
                    })
                }
                // this.title = $(this).parent().prev().attr("title");
                // if ($(this).parent().prev().attr("popContent") != null) {
                //     $(this).popover({content: $(this).parent().prev().attr("popContent"), trigger:'hover', width:'500px', placement:'auto-right'});
                // }
            })
        }
    });
    $.parser.parse('#' + itemId);  //解析checkbox
}

objScreen.toggle = function (aItemCat) {
    if ($('div[title="' + aItemCat + '"]').css('display') == 'block') {
        //收起来的时候，校验必填项目
        $('div[title="' + aItemCat + '"]').css({'display': 'none'});
        $('div[title="' + aItemCat + '"]').prev().addClass('itemCat-fold');
        objScreen.valiForm(aItemCat);
    } else {
        $('div[title="' + aItemCat + '"]').css({'display': 'block'});
        $('div[title="' + aItemCat + '"]').prev().removeClass('itemCat-fold');
    }
}
///展现评分表内容
objScreen.showEvalSheet = function (itemId, asmtId, aSheetTitle) {

    //打开 弹出框
    var index = layer.open({
        type: 2,
        title: aSheetTitle,
        area: ['80%', '80%'],
        zIndex: 19911102,//这是个大坑！！！！ 默认是19891014 远远大于量表下拉框的zIndex 导致下拉框的数据看不到！！！
        content: '/sds/sdsqcformshow/showASMT?asmtId=' + asmtId + "&mrListId=" + objScreen.mrListId + "&itemId=" + itemId,
        skin: 'layer-ext-hisui',
        scrollbar: false//为了禁止父页面滚动条滚动
    });
    this.layerIndex = index;

    //监听子页面的postMessage
    function receiveMessage(event) {
        if (event.data.type == "save") {
            //评分确认先给input隐藏组件赋值
            $("#" + itemId).siblings().each(function (i, e) {
                if (e.type == 'hidden') $(e).val(event.data.score)
            })
            objScreen.setItemVal(itemId, event.data.level, event.data.score);
            setTimeout(function () {
                layer.close(index);
            }, 1000);
            // 主动触发input事件
            $("#" + itemId).trigger('input');
        }
    }

    if (window.addEventListener) {
        // 在现代浏览器中使用addEventListener
        window.addEventListener('message', receiveMessage, false);
    } else if (window.attachEvent) {
        // 在IE8及以下版本中使用attachEvent
        window.attachEvent('onmessage', receiveMessage);
    }
}
objScreen.setItemVal = function (itemId, atext, tsval) {
    var itemClass = $('#' + itemId).attr('class');
    if (itemClass.indexOf('combox') > -1) {
        objScreen.CreatCombo(itemId, false);
        $('#' + itemId).combobox('setValue', tsval, atext);
    } else {
        $('#' + itemId).val(tsval)
    }
}

objScreen.ExportRep = function () {
}

//取值
function Common_GetSDValue(key, type) {
    var res = "";
    try {
        switch (type) {
            case "CheckGroup":
                $("input[type='checkbox'][name=" + key + "]:checked").each(function () {
                    //  选中复选框中的值
                    res += $(this).val() + ",";
                });
                res = res.substring(0, res.length - 1)
                break;
            case "RadioGroup":
                res = $("input[type='radio'][name=" + key + "]:checked").val();
                break;
            case "Combo":
                res = $("#" + key).combobox("getValue");
                break;
            case 'Date':
                res = $('#' + key).datebox("getValue");
                break;
            case 'DateT':
                res = $('#' + key).datetimebox("getValue");
                break;
            default:
                if (type.indexOf('numberbox') > -1) {  	//时间框
                    res = $('#' + key).datetimebox('getValue');
                } else if (type.indexOf('datebox') > -1) {  			//日期
                    res = $('#' + key).datebox('getValue');
                } else if (type.indexOf('datetimebox') > -1) {  	//时间框
                    res = $('#' + key).datetimebox('getValue');
                } else if (type.indexOf('combobox') > -1) {  		//下拉框
                    res = $('#' + key).combobox('getValue');
                } else {
                    res = $("#" + key).val();
                }
                break;
        }
    } catch (e) {
        res = $("#" + key).val();
    }
    return res;
}

function Common_CheckboxToSDDic() {
    var itemId = arguments[0];
    var DicType = arguments[1];
    var columns = arguments[2] ? arguments[2] : 4;

    var dicArr = JSON.parse($("#" + itemId + "_Row").attr("dic"));
    var len = dicArr.length;

    //当前填写窗口的宽=input宽-复选框宽度
    var listHtml = "";
    var divWidth = $(".itemCat").outerWidth() * 0.35 - 24; //$(".itemTR div").outerWidth() - 24;
    //获取默认字体大小，用以计算展现字典所需高度
    var style = document.body.currentStyle || document.defaultView.getComputedStyle(document.body, '')
    var dFontSize = style.fontSize.replace('px', '');
    for (var index = 0; index < len; index++) {
        var dicSub = dicArr[index];
        //计算一行能放置的字数
        var divWordCount = Math.floor(divWidth / dFontSize);
        var divheight = Math.ceil(dicSub.desc.length / divWordCount) * 28;
        listHtml += "<div style='padding-top:5px;height:" + divheight + "px;'>";
        listHtml += "<input class='hisui-checkbox' value='" + dicSub.code + "' type='checkbox' data-options='onCheckChange:function(event,value){objScreen.fireEvent(\"" + itemId + "\",\"\")}' " +
            "style='display:inline-block;' label='" + dicSub.desc + "' name='" + itemId + "' id='" + itemId + dicSub.id + "'>"
        listHtml += "</div>"
    }
    $('#' + itemId).html(listHtml);
    $.parser.parse('#' + itemId);  //解析checkbox
}

//单选字典
function Common_RadioToSDDic() {
    var itemId = arguments[0];
    var DicType = arguments[1];
    var dicArr = JSON.parse($("#" + itemId + "_Row").attr("dic"));
    var len = dicArr.length;

    var columns = len;
    if (len > 3) columns = 2;
    var count = parseInt(len / columns) + 1;
    var per = Math.round((1 / columns) * 100) + '%';   //每列所在百分比
    var listHtml = ""
    for (var index = 0; index < count; index++) {
        var radlen = (((index + 1) * columns) < len) ? (index + 1) * columns : len;
        listHtml += "<div style='padding-top:5px;'>";
        for (var dicIndex = index * columns; dicIndex < radlen; dicIndex++) {
            var dicSub = dicArr[dicIndex];
            listHtml += "<div style=' display: inline-block;float:left;padding-right:10px;'>"
            listHtml += "<input class='hisui-radio' value='" + dicSub.code + "' type='radio' data-options='onCheckChange:function(event,value){objScreen.fireEvent(\"" + itemId + "\",\"\")}' " +
                "label='" + dicSub.desc + "' name='" + itemId + "' id='" + itemId + dicSub.id + "'>"
            listHtml += "</div>";
        }
        listHtml += "</div>"
    }
    $('#' + itemId).html(listHtml);
    $.parser.parse('#' + itemId);
}

function Unhtml(strDicList, o, n) {
    var reg = new RegExp(o, 'g')
    return strDicList.replace(reg, n)
}


function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + date.getHours() + seperator2 + date.getMinutes()
        + seperator2 + date.getSeconds();
    return currentdate;
}

$(function () {
    // 初始化表单内容
    objScreen.InitViewScreen();
    // 初始化按钮状态
    objScreen.InitMrButtons();
    // 加载各种事件
    objScreen.LoadEvent();

});